package orbito.entity;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.util.Iterator;
import java.util.LinkedList;

import orbito.graphics.Viewport;
import orbito.util.Vec2;

public class Trail {
	
	int maxPointCount;
	LinkedList<Vec2> points;

	Vec2 savedPoint;
	Vec2 savedVelocity;
	Vec2 lastPoint;
	
	public Trail(int maxPointCount) {
		this.maxPointCount = maxPointCount;
		this.points = new LinkedList<Vec2>();
	}
	
	public void addPoint(Vec2 point, Vec2 velocity) {
		if (savedPoint == null) {
			savedPoint = point;
			savedVelocity = velocity;
			points.addLast(point);
		} else if (Vec2.getRelativeAngle(savedVelocity, velocity) > 0.2) {
			savedPoint = point;
			savedVelocity = velocity;
			
			points.addLast(point);
			while (points.size() > maxPointCount) {
				points.removeFirst();
			}
		}
		
		lastPoint = point;
	}
	
	public void clearPoints() {
		savedPoint = savedVelocity = lastPoint = null;
		points.clear();
	}
	
	public void renderInfo(Graphics2D g, Viewport viewport, AffineTransform tx, double t, double dt) {
		Iterator<Vec2> iter = points.iterator();
		if (iter.hasNext()) {
			Vec2 a = iter.next();
			while (iter.hasNext()) {
				Vec2 b = iter.next();
				renderTrail(g, tx, a, b);
				a = b;
			}
			
			if (lastPoint != null) {
				renderTrail(g, tx, a, lastPoint);
			}
		}
	}
	
	private void renderTrail(Graphics2D g, AffineTransform tx, Vec2 a, Vec2 b) {
		Vec2 t1 = a.transform(tx);
		Vec2 t2 = b.transform(tx);
		g.drawLine((int) t1.x, (int) t1.y, (int) t2.x, (int) t2.y);
	}
}
